package com.example.sicnuaccountingapp.ui.profile

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import com.example.sicnuaccountingapp.R
import com.example.sicnuaccountingapp.databinding.DialogChangePasswordBinding
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class ChangePasswordDialog : DialogFragment() {
    private var _binding: DialogChangePasswordBinding? = null
    private val binding get() = _binding!!

    private val viewModel: ProfileViewModel by viewModels({ requireParentFragment() })

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        _binding = DialogChangePasswordBinding.inflate(LayoutInflater.from(context))

        return AlertDialog.Builder(requireContext())
            .setTitle(R.string.change_password)
            .setView(binding.root)
            .setPositiveButton(R.string.save, null)
            .setNegativeButton(R.string.cancel, null)
            .create()
            .apply {
                setOnShowListener { dialog ->
                    (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)
                        .setOnClickListener {
                            changePassword()
                        }
                }
            }
    }

    private fun changePassword() {
        val currentPassword = binding.currentPasswordEdit.text.toString()
        val newPassword = binding.newPasswordEdit.text.toString()
        val confirmNewPassword = binding.confirmNewPasswordEdit.text.toString()

        if (currentPassword.isBlank() || newPassword.isBlank() || confirmNewPassword.isBlank()) {
            Toast.makeText(context, R.string.please_fill_all_fields, Toast.LENGTH_SHORT).show()
            return
        }

        if (newPassword != confirmNewPassword) {
            Toast.makeText(context, R.string.passwords_do_not_match, Toast.LENGTH_SHORT).show()
            return
        }

        viewModel.changePassword(currentPassword, newPassword)
        dismiss()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        const val TAG = "ChangePasswordDialog"

        fun newInstance(): ChangePasswordDialog {
            return ChangePasswordDialog()
        }
    }
} 